#!/usr/bin/awk -f

#WAP站点PV、UV、VV统计程序#
#统计规则#
#1、去除特殊400类错误，如180.114.101.117 - - [21/Dec/2011:00:00:06 +0800] "-" 400 0 "-" "-" "-" "-" ""
#2、PV只计有效访问，去除403、404、500、502等错误，其他大于400类错误，计入VV量和UV量
#3、每天访问站点的COOKIE去重计算总和计入UV量#
#4、访问URL为/pvs的计入VV总量
#
#CLIENT统计UV、PV、VV规则
#1、PV、UV、VV去除特殊类400错误，其他均计入统计量
#
#程序执行方式(python脚本外部调用)#
#awk -f functions.awk -f log_wap.awk xxx.log

BEGIN {
#if(!date_format) {
#        error = "true";
#        print "usage: awk -f functions.awk -f log_wap.awk -v date_format = (day|hour) file ...";
#        exit;
#    }
#
    pid = "a8c022bcd2adcbee";
    FS = "\"";
    arr[1] = "";
    begin_time();
}

{
    delete resCode;
    #按统计规则1去除不符合规则的日志
    if($0 !~ /GET|POST/) {
        results_error++;
        next;
    }

    #Count VV For WAP
    if(match($2,/(GET|POST){1}\s+\/pvs.*?$/,results) != 0) {
        results_success_vv++;
    }

    #Count UV For WAP
    gsub(/\\x22/,"",$12);
    parse_cookie($12,results_success_uv);

    #Count PV For WAP
    #去除403、404、500、502等错误
    split($3,resCode," ");
    if(resCode[1] >= 400)
    {
        next;
    }
    results_success_pv++;
}

END {
    if(!error) {
        wap_pv = results_success_pv;
        wap_vv = results_success_vv;
        wap_uv = length(results_success_uv);
        end_time();
        runtime = Time_end - Time_begin;
	    strJson = "{\"pid\":\""pid"\",";
	    strJson = strJson"\"pvResults\":\""wap_pv"\",";
	    strJson = strJson"\"vvResults\":\""wap_vv"\",";
	    strJson = strJson"\"uvResults\":\""wap_uv"\",";
	    strJson = strJson"\"results_error\":\""results_error"\",";
	    strJson = strJson"\"runTime\":\""runtime"\"";
        strJson = strJson"}";
        print strJson;
    }
}

function parse_cookie(str,array) {
    delete arr;
    if(index(str,";") == 0) {
        array[str] += 1;
    }else {
        split(str,arr,";");
        array[arr[1]] += 1;
    }
}
